<style lang="less" scoped>
.permission-list {
  position: relative;
  padding: 20px;
  border: 1px solid #3f95ff;
  max-height: 200px;
  overflow: auto;
  .select-all {
    position: absolute;
    right: 20px;
    z-index: 10;
  }
}
</style>
<template>
  <div class="comp-new">
    <el-form
      ref="newForm"
      :rules="rules"
      :model="newForm"
      :label-width="150 + 'px'"
    >
      <el-form-item label="所属：">{{
        activeData ? activeData.homeName : orgNames.join("-")
      }}</el-form-item>
      <el-form-item label="真实姓名：" prop="name">
        <el-input placeholder="请输入" v-model.trim="newForm.name"></el-input>
      </el-form-item>
      <el-form-item label="登录账号：" prop="accountname">
        <el-input
          placeholder="请输入"
          type="text"
          v-model.trim="newForm.accountname"
        ></el-input>
      </el-form-item>
      <el-form-item label="登录密码：" prop="accountpassword">
        <el-input
          placeholder="请输入"
          type="password"
          v-model.trim="newForm.accountpassword"
        ></el-input>
      </el-form-item>
      <el-form-item label="选择角色：" prop="roleId">
        <el-select v-model="newForm.roleId" placeholder="请选择">
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item, index) in roleList"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择权限：" prop="permissionsId" v-if="false">
        <div class="permission-list">
          <div class="select-all">
            <el-button
              type="green"
              v-if="isAllSelected"
              @click="cancelSelectAll"
              >取消全选</el-button
            >
            <el-button type="green" v-else @click="selectAll">全选</el-button>
          </div>

          <el-tree
            ref="tree"
            node-key="id"
            :props="props"
            :data="permissionList"
            show-checkbox
            :indent="36"
            :default-checked-keys="checkedKeys"
            :default-expanded-keys="defaultExpandedKeys"
            @check-change="handleCheckChange"
          >
          </el-tree>
          <!-- :default-checked-keys="checkedKeys" -->
        </div>
      </el-form-item>
      <el-form-item label="手机号：">
        <el-input placeholder="请输入" v-model.trim="newForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input placeholder="请输入" v-model.trim="newForm.email"></el-input>
      </el-form-item>
      <el-form-item label="访问规则：">
        <p>继承当前账号访问规则：</p>
        <p>星期：周一,周二,周三,周四,周五,周六,周日</p>
        <p>时间：0001,2359</p>
      </el-form-item>
      <!-- <el-form-item label="菜单设置：" >
		  		<el-checkbox-group v-model="checkedPermission">
				    <el-checkbox :label="item.id" v-for="(item, index) in permissionList" :key="index">{{item.name}}</el-checkbox>
				</el-checkbox-group>
		  	</el-form-item> -->
    </el-form>
  </div>
</template>
<script>
import { mapState } from "vuex";
export default {
  name: "newRecordAccount",
  props: {
    activeData: {
      type: Object,
      default() {
        return null;
      },
    },
    orgNames: {
      type: Array,
      default() {
        return [];
      },
    },
    orgId: {
      type: String,
      default: "",
    },
  },
  computed: {
    ...mapState(["siteInfos"]),
  },
  watch: {
    activeData() {
      this.initForm();
    },
    checkedPermission(val) {},
  },
  data() {
    const validatePass = (rule, value, callback) => {
      const reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/;
      if (!reg.test(value)) {
        callback(
          new Error("请输入8-16位字符,可使用大写字母,小写字母,数字或符号的至少三种组合")
        );
      } else {
        callback();
      }
    };
    return {
      newForm: {},
      loading: false,
      permissionList: [],
      checkedPermission: [],
      roleList: [],

      props: {
        label: "name",
        children: "childList",
      },
      permissionList: [],
      checkedKeys: [],
      defaultExpandedKeys: [],
      isAllSelected: false,
      rules: {
        name: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
        accountname: [
          { required: true, message: "请输入登录账号", trigger: "blur" },
        ],
        accountpassword: [
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
        email: [{ type: "email", message: "邮箱格式不正确", trigger: "blur" }],
      },
    };
  },
  created() {
    this.initForm();
    this.getRoles();
    this.getPermission();
  },
  methods: {
    initForm() {
      if (this.activeData) {
        let {
          id,
          name,
          accountname,
          accountpassword,
          phone,
          email,
          homeId,
          homeName,
          roleId,
          permissionsList,
        } = this.activeData;
        this.newForm = {
          id,
          name,
          accountname,
          accountpassword,
          phone,
          email,
          homeId,
          homeName,
          roleId,
        };
        let permissionsId = this.getPermissionsId(permissionsList);
        this.newForm.permissionIds = permissionsId.join(",");
      } else {
        this.newForm = {};
        if (this.siteInfos.userType == 2) {
          this.newForm.departmentId = this.orgId;
        } else if (this.siteInfos.userType == 1) {
          this.newForm.homeId = this.orgId;
        }
        if (this.$refs["newForm"]) {
          this.$refs["newForm"].resetFields();
        }
      }
    },

    getPermission() {
      this.$get("/systemsetup/systemsetup/permissionsTreeList").then((res) => {
        this.permissionList = res.data.childList;
      });
    },
    getPermissionsId(permissionList) {
      let ids = [];
      permissionList.forEach((item) => {
        if (item.flag) {
          ids.push(item.id);
          this.defaultExpandedKeys.push(item.pid);
          if (!item.childList) {
            this.checkedKeys.push(item.id);
          }
        }
        if (item.childList) {
          let childIds = this.getPermissionsId(item.childList);
          ids = [...ids, ...childIds];
        }
      });
      return ids;
    },
    handleCheckChange(data) {
      let checkedKeys = this.$refs.tree.getCheckedKeys();
      let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
      this.newForm.permissionIds = [checkedKeys, halfCheckedKeys].join(",");
    },
    getRoles() {
      this.$get("/systemsetup/systemsetup/roleListNoPage").then(
        (res) => {
          this.roleList = res.data;
        },
        (err) => {
          //
        }
      );
    },
    selectAll() {
      this.isAllSelected = true;
      this.$refs.tree.setCheckedNodes(this.permissionList);
    },
    cancelSelectAll() {
      this.isAllSelected = false;
      this.$refs.tree.setCheckedNodes([]);
      this.$refs.tree.setCheckedKeys([]);
    },
    submitAction() {
      this.$refs["newForm"].validate((valid) => {
        if (valid) {
          this.$emit("submitting");
          this.loading = true;
          let params = Object.assign({}, this.newForm);
          delete params.createtime;
          delete params.homeName;
          delete params.isUse;
          delete params.type;

          let url = "";
          if (params.id) {
            url = "/systemsetup/systemsetup/userUpdate";
          } else {
            url = "/systemsetup/systemsetup/userAdd";
          }
          // params.permissionIds = this.checkedPermission.join(',')
          params.type = this.siteInfos.userType;
          this.$ajax({
            url: url,
            method: "post",
            data: params,
          }).then(
            (data) => {
              this.loading = false;
              this.$message({
                type: "success",
                message: "保存成功",
                center: true,
              });
              this.$emit("success", data);
            },
            (error) => {
              this.loading = false;
              this.$emit("fail");
              this.$message.error(error.msg);
            }
          );
        } else {
          return false;
        }
      });
    },
    cancelAction() {
      this.$emit("cancel");
    },
    // resetForm () {
    // 	this.newForm = {}
    // 	this.$refs['newForm'].resetFields()
    // }
  },
};
</script>
